﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FlashCards.WebApplication.DAL;
using FlashCards.Models;
using FlashCards.WebApplication.Maintenance;

namespace FlashCards.WebApplication.Pages
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (HttpContext.Current.Request.QueryString.AllKeys.Contains("action"))
                {
                    string action = HttpContext.Current.Request.QueryString["action"];
                    if (action == "logout")
                    {
                        if (Session["LoggedUser"] != null)
                            Session.Remove("LoggedUser");
                    }
                }
            }
        }

        protected void RegisterUser(object sender, EventArgs e)
        {
            Validate("NewUser");
            if (IsValid)
            {
                User user = new User(TextBoxNewLogin.Text, TextBoxNewPassword.Text);
                DataBaseConnector.AddNewUser(user);
                Session.Add("LoggedUser", user);
                Response.Redirect("Default.aspx");
            }
        }

        protected void LoginUser(object sender, EventArgs e)
        {
            Validate("User");
            if (IsValid)
            {
                User user = DataBaseConnector.GetUserByName(TextBoxLogin.Text);
                if (user != null)
                {
                    if (user.Password == TextBoxPswd.Text)
                    {
                        Session.Add("LoggedUser", user);
                        Response.Redirect("Default.aspx");
                    }
                }
            }
        }

        /// <summary>
        /// Funkcja sprawdza czy podany login do rejestracji:
        /// - nie jest już zajęty
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ValidateLogin(object sender, ServerValidateEventArgs e)
        {
            if (DataBaseConnector.GetUserByName(TextBoxNewLogin.Text) != null)
            {
                e.IsValid = false;
            }
        }
    }
}